package com.orange.cloud.common.redis.utils;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class CodecUtils {
    /**
     * string to md5
     * @param source
     * @return
     * @throws UnsupportedEncodingException
     * @throws NoSuchAlgorithmException
     */
    public static String MD5(String source) throws UnsupportedEncodingException, NoSuchAlgorithmException {
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            byte[] md5Bytes = md5.digest(source.getBytes("utf-8"));
            return bytesToHexString(md5Bytes, null).toLowerCase();
    }

    /**
     * bytes to hexString
     * @param src
     * @param bytePrefix
     * @return
     */
    public static String bytesToHexString(byte[] src, String bytePrefix) {
        StringBuilder stringBuilder = new StringBuilder("");
        if (src == null || src.length <= 0) {
            return null;
        }
        for (int i = 0; i < src.length; i++) {
            int v = src[i] & 0xFF;

            if (bytePrefix != null && bytePrefix.length() > 0) {
                stringBuilder.append(bytePrefix);
            }

            String hv = Integer.toHexString(v).toUpperCase();
            if (hv.length() < 2) {
                stringBuilder.append(0);
            }
            stringBuilder.append(hv);
        }
        return stringBuilder.toString();
    }
}
